"""A small prompting class.

Danny Yoo (dyoo@hkn.eecs.berkeley.edu)

This hasn't been too documented yet.  There's some sample uses on
the bottom with the test() function below.
"""


## First, let's see if we can load up readline and make raw_input()
## nice to work with.
try:
    import readline
except ImportError: pass

import sys
import pprint

class Prompt:
    def __init__(self, name, quit_str = 'quit', quit_cmd=sys.exit,
                 callback=None):
        self.name = name
        self.quit_str = quit_str
        self.quit_cmd = quit_cmd
        self.callback = callback
        
    def promptLoop(self):
        while 1:
            try:
                s = raw_input('[%s] >>> ' % self.name)
                if s == self.quit_str:
                    raise EOFError
                elif s and self.callback:
                    result = self.callback(s)
                    if result != None:
                        pprint.pprint(result)
            except (EOFError, KeyboardInterrupt):
                print
                return self.quit_cmd



######################################################################

## Note: I should probably use the unit testing modules.
def test():
    def echoCallback(s):
        print s
    p = Prompt('test', callback=echoCallback)
    p.promptLoop()


if __name__ == '__main__':
    test()
